﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Model
{
    /// <summary>
    /// 同步上下文
    /// 在异步中await之后，的代码调用，将会是Post重载方法中的一个SendOrPostCallback委托。
    /// </summary>
    public class OneThreadSynchroniztionContext :SynchronizationContext
    {
        private readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();

        public void Add(Action action)
        {
           
            this.queue.Enqueue(action);
        }

        public void Update()
        {
           // Console.Title = queue.Count + "";
            while (true)
            {
                if (!this.queue.TryDequeue(out Action action))
                {
                    return;
                }
                action();
            }
        }

        public override void Post(SendOrPostCallback d, object state)
        {
            this.Add(() => { d(state); });
        }

    }
}
